<!-- 考勤统计 -->
<template>
  <ContainerLayoutV2 ref="containerLayoutRef" class="attendance-personal">
    <template #form>
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <UserInput v-model="queryForm.user" />
        <DeptCascader v-model="queryForm.deptIds" :multiple="false" />
        <TimeSlotDatePicker label="日期" v-model="queryForm.date" styleWidth="250px" :shortcuts="[]" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template #toolbar>
      <ExcelExportButton :headerParams="exportHeaderParams" :table-data="exportTableData" fileName="考勤信息" />
    </template>
    <template #tables>
      <el-table :data="tableData" v-loading="loading" element-loading-text="加载中..." scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
        <el-table-column type="index" label="序号" width="54" fixed />
        <el-table-column label="部门" width="100" fixed>
          <template #default="scope">{{ scope.row.deptName }}</template>
        </el-table-column>
        <el-table-column prop="userNick" label="姓名" width="100" fixed />
        <el-table-column prop="late_num" label="迟到" width="54" fixed />
        <el-table-column prop="early_num" label="早退" width="54" fixed />
        <el-table-column prop="lack_clockin_num" label="旷卡" width="54" fixed />
        <el-table-column prop="reissue_clockin_num" label="补卡" width="54" fixed />
        <el-table-column prop="lack_work_num" label="旷工(天)" width="80" fixed />
        <el-table-column>
          <template #header>
            <div style="text-align: center">{{ tableHeader }}请假类型（天）</div>
          </template>
          <el-table-column v-for="item in tebleColumnsHeader" :prop="`Category${item.dictValue}`" :label="item.dictLabel" width="80" />
          <el-table-column prop="remark" label="备注" width="80" />
        </el-table-column>
        <el-table-column>
          <template #header>
            <div style="text-align: center">年度请假情况汇总</div>
          </template>
          <el-table-column v-for="item in tebleColumnsHeader" :prop="`holidayCategory${item.dictValue}`" :label="`${item.dictLabel}`" width="80" />
          <el-table-column prop="remark" label="总计" width="80" />
        </el-table-column>
      </el-table>
    </template>
  </ContainerLayoutV2>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import ContainerLayoutV2 from '../layout/ContainerLayoutV2.vue'
import DeptCascader from '../layout/FormTableLayout/DeptCascader.vue'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import UserInput from '../layout/FormTableLayout/UserInput.vue'
import { useHolidayCategoryStore, useUsersStore, useDeptStore } from '../stores'
import { formatDate } from '../utils'
import { Refresh, Search } from '@element-plus/icons-vue'
import api from '../api'
import { ElMessage } from 'element-plus'
import ExcelExportButton from '../layout/ButtonToolbar/ExcelExportButton.vue'

const containerLayoutRef = ref<InstanceType<typeof ContainerLayoutV2> | null>(null)
// 请假类型
const holidayCategoryList = useHolidayCategoryStore().getAllState()
// 用户列表
// const usersList = useUsersStore().userAllList
const loading = ref(false)
// 表格
const currentDeptId = ref()
const tableHeight = ref(500)
const tableData = ref<any[]>([])
const leaveList = ref<any[]>([])
const tableHeader = ref('')
const tebleColumnsHeader = ref<any[]>([])
// 表单
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [],
  deptIds: [] as string[] | number[],
})

const exportTableData = ref<any[]>([])
const exportHeaderParams = ref<any[]>([
  // { title: '序号', value: 'index', width: 54 },
  { title: '部门', value: 'deptName', width: 10 },
  { title: '姓名', value: 'userNick', width: 20 },
  { title: '迟到', value: 'late_num', width: 10 },
  { title: '早退', value: 'early_num', width: 10 },
  { title: '旷卡', value: 'lack_clockin_num', width: 10 },
  { title: '补卡', value: 'reissue_clockin_num', width: 10 },
  { title: '旷工(天)', value: 'lack_work_num', width: 12 },
  { title: '', children: [] },
  { title: '年度请假情况汇总', children: [] },
])

onMounted(async () => {
  await initDepIds()

  // 设置表格高度
  await setTableHeight()

  // 按假期类型设置表头
  await setTableColumnsHeader()
})

/**
 * 初始化部门ID
 */
const initDepIds = () => {
  const list = useDeptStore().getAllListState()
  const item = list.find((res: any) => res.deptId === useUsersStore().user.deptId)

  const deptIds = item.ancestors.split(',').map(Number).slice(1).concat(item.deptId)
  queryForm.deptIds = deptIds
}

/**
 * 设置表格高度
 *
 * 如果存在表格容器，则获取该容器的高度并赋值给表格高度变量
 */
const setTableHeight = () => {
  if (containerLayoutRef.value && containerLayoutRef.value.tableContainer) {
    const tableContainer = containerLayoutRef.value.tableContainer
    tableHeight.value = tableContainer.offsetHeight
  }
}

/**
 * 设置表格列头
 *
 * 该函数用于设置表格的列头数据。
 */
const setTableColumnsHeader = () => {
  tebleColumnsHeader.value = holidayCategoryList.map((item) => {
    return {
      dictValue: item.dictValue,
      dictLabel: item.dictLabel,
    }
  })

  exportHeaderParams.value[7].children = [
    ...tebleColumnsHeader.value.map((item) => {
      return { title: `${item.dictLabel}`, value: `Category${item.dictValue}`, width: 12 }
    }),
  ]
  exportHeaderParams.value[8].children = [
    ...tebleColumnsHeader.value.map((item) => {
      return { title: `${item.dictLabel}`, value: `holidayCategory${item.dictValue}`, width: 12 }
    }),
  ]

  // console.log(exportHeaderParams.value)
}
/**
 * 获取当前部门用户请假信息列表的异步函数
 *
 * @returns 无返回值
 */
const getLeaveList = async () => {
  tableHeader.value = ''

  if (queryForm.date.length < 2) {
    ElMessage.error('必须选择起止日期！')
    return
  }
  const params = {
    deptId: currentDeptId.value,
    pageSize: 99999,
    startDate: formatDate(queryForm.date[0], 'yyyy-MM-dd'),
    endDate: formatDate(queryForm.date[1], 'yyyy-MM-dd'),
  }
  tableHeader.value = params.startDate + ' 至 ' + params.endDate
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }
  exportHeaderParams.value[7].title = `${tableHeader.value}请假类型（天）`
  // if (vacationState.value > -1) {
  //   // Object.assign(params, { leaveStatus: vacationState.value })
  //   Object.assign(params, { leaveStatus: vacationState.value })
  // }
  // leaveList.value = await api.Leave.getList(params)
  leaveList.value = await api.Holiday.getAttendanceList(params)

  // console.log(leaveList.value)
}

/**
 * 聚合数据
 *
 * 该函数用于处理请假列表数据，根据当前月份聚合请假信息和请假类型。
 */
const dataAggregation = async () => {
  // 用户 获取当前部门用户列表
  // const users = usersList.filter((item) => item.deptId === deptId)
  const users = leaveList.value

  tableData.value = users.map((user: any) => {
    // 提前将 userLeaveList 按 userId 分组
    // const userLeaves = userLeaveList.filter((e: any) => e.userId === user.userId)

    // 创建一个对象，用于存储当前用户的假期类型数据
    const userHolidays: any = {}

    // 遍历假期类型，填充 userHolidays
    holidayCategoryList.forEach((item: any) => {
      // 聚合：按日期
      const temp = user.leaveDataList.find((e: any) => e.leaveCategory === item.dictValue)
      userHolidays[`Category${item.dictValue}`] = temp?.num || 0

      // 聚合：按年
      const temp2 = user.holidayList.find((e: any) => e.holidayCategory === item.dictValue)
      userHolidays[`holidayCategory${item.dictValue}`] = temp2?.holidayUsedNum || 0
    })

    // 返回最终的用户数据
    return {
      ...user,
      ...userHolidays,
    }
  })
  // tableData.value
  exportTableData.value = tableData.value
  // console.log(tableData.value)
}

/**
 * 处理点击提交按钮的事件
 *
 * @returns 无返回值
 */
const handleClickBtnSubmit = async () => {
  const deptId = Object.assign([], queryForm.deptIds).pop()
  currentDeptId.value = deptId
  loading.value = true
  // 用户列表
  await getLeaveList()

  await dataAggregation()
  loading.value = false
}

const handleClickBtnReset = () => {
  queryForm.user = ''
  queryForm.date = []
  initDepIds()
  handleClickBtnSubmit()
}
</script>
